package com.ruoyi.user.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.TXIMConstants;
import com.ruoyi.common.core.domain.model.TXIMUserAccount;
import com.ruoyi.user.service.TXIMUserService;
import com.ruoyi.user.utils.IMRestTemplateUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;


/**
 * Im 用户服务实现类
 *
 * @author mrj
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class TXIMUserServiceImpl implements TXIMUserService {

    private final RestTemplate restTemplate;

    @Override
    public boolean accountImport(TXIMUserAccount userAccount) {
        HttpHeaders headers = IMRestTemplateUtils.setIMHttpHeaders();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("UserID", userAccount.getUserId());
        jsonObject.put("Nick", userAccount.getNick());
        jsonObject.put("FaceUrl", "https://im.sdk.qcloud.com/download/tuikit-resource/avatar/avatar_12.png");
        HttpEntity<JSONObject> requestEntity = new HttpEntity<>(jsonObject, headers);
        ResponseEntity<JSONObject> resultEntity = restTemplate.exchange(TXIMConstants.ACCOUNT_IMPORT + IMRestTemplateUtils.getIMUrlParmas(),
                HttpMethod.POST,
                requestEntity, JSONObject.class);
        String actionStatus = resultEntity.getBody().get("ActionStatus").toString();
        if ("OK".equals(actionStatus)) {
            return true;
        } else {
            log.error("账号导入失败");
            log.error("失败信息: {}", resultEntity.getBody().get("ErrorInfo"));
            log.error("失败编码: {}", resultEntity.getBody().get("ErrorCode"));
            return false;
        }
    }

}
